//
//  MaskView+Loading.swift
//  Asman
//
//  Created by 李旭峰 on 7/9/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import Foundation
import SnapKit

fileprivate var cx_loadingViewKey:Void?
fileprivate var cx_maskViewKey:Void?
extension UIView {
    fileprivate var cx_maskView:UIView? {
        set{
            objc_setAssociatedObject(self, &cx_maskViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &cx_maskViewKey) as? UIView
        }
    }
    fileprivate var loadMaskView:CXPaymentLoadingView?{
        set{
            objc_setAssociatedObject(self, &cx_loadingViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &cx_loadingViewKey) as? CXPaymentLoadingView
        }
    }
  func cx_showLoading(with message:String? = nil,cancelAction:(()->())? = nil){
      DispatchQueue.main.async {
          if self.loadMaskView != nil {
              self.cx_maskView?.removeFromSuperview()
              self.cx_maskView = nil
              self.loadMaskView?.removeFromSuperview()
              self.loadMaskView = nil
          }
          self.cx_maskView = UIView()
          self.cx_maskView?.isUserInteractionEnabled = true
          self.cx_maskView?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
          self.addSubview(self.cx_maskView!)
          self.cx_maskView?.snp.makeConstraints({ (make) in
              make.leading.top.trailing.bottom.equalToSuperview()
          })
          self.loadMaskView = CXPaymentLoadingView()
          self.loadMaskView?.cancelAction = cancelAction
          self.loadMaskView?.config()
          self.loadMaskView?.isUserInteractionEnabled = true
          self.addSubview(self.loadMaskView!)
          self.loadMaskView?.snp.remakeConstraints({ (make) in
              make.centerX.width.equalToSuperview()
              make.top.height.equalToSuperview()
          })
          self.loadMaskView?.loading(with: message)
      }
    }
    func cx_removeLoading(){
        DispatchQueue.main.async {
            if self.loadMaskView != nil {
              self.cx_maskView?.removeFromSuperview()
              self.cx_maskView = nil
              self.loadMaskView?.removeFromSuperview()
              self.loadMaskView = nil
            }
        }
    }
}
